package myzzyl.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import myzzyl.constants.ErrorConstants;
import myzzyl.exception.BusinessException;
import myzzyl.response.BaseResponse;
import myzzyl.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@RestController
@Slf4j
@Tag(name = "通用接口")
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public BaseResponse<String> upload(@RequestPart MultipartFile file) throws IOException {
        log.info("文件上次：{}", file);
        // 判断文件是否为空
        if(file == null || file.isEmpty()) {
            throw new BusinessException(ErrorConstants.FILE_IS_NULL);
        }
        // 判断文件格式
        String originalFilename = file.getOriginalFilename();
        if(originalFilename == null || !originalFilename.contains(".")) {
            throw new BusinessException(ErrorConstants.FILE_PATTERN_ERROR);
        }
        // 获取文件扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        // 构造文件名
        String prefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd/"));
        String key = prefix + IdUtil.fastSimpleUUID() + extension;

        String url = aliOssUtil.store(key, file.getInputStream());
        return BaseResponse.success(url);
    }


}
